import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/11/4 15:23
 */

//创建一个类来描述一个任务
class MyTask implements Comparable<MyTask> {
    //任务具体要干啥
    private Runnable runnable;
    //任务具体什么时候干，保存任务要执行的毫秒级时间戳
    private long time;

    // after 时间间隔
    public MyTask(Runnable runnable, long after) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+after;
    }
    public void run(){
        runnable.run();
    }

        //获取时间
    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
}


class MyTimer{
    //存放多个任务，带有阻塞功能，保证线程安全
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable,long delay){
        MyTask task = new MyTask(runnable,delay);
        queue.put(task);//把任务加进来了

        //插入成功，唤醒扫描线程，判断是否时间到了的任务
        synchronized (locker){
            locker.notify();
        }
    }


                      //扫描线程
    private Object locker = new Object();
    public MyTimer(){
        Thread t = new Thread(()->{
           while (true){
               try {
                   //1.取出队首任务
                   MyTask task = queue.take();
                   //再判断当前任务时间到了没有？
                   long curTime = System.currentTimeMillis();//获取当前时间
                   if(curTime < task.getTime()){
                       //时间没到，把任务再加回来
                       queue.put(task);

                       synchronized (locker){
                           locker.wait(task.getTime()-curTime);
                       }

                   }else{
                       //时间到了
                       task.run();
                   }

               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        t.start();
    }
}


public class Test {
    public static void main2(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello!!!");
            }
        },3000);
    }




    public static void main(String[] args) {
        MyTimer mytimer = new MyTimer();
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer");
            }
        },3000);

        System.out.println("main");
    }
}
